<?php

namespace app\health\controller;

use app\health\model\HealthCouponList;
use app\health\validate\OrderValidate;
use think\Db;

class UserCoupon extends ApiBase
{
    protected function _initialize()
    {
        parent::_initialize();
        //处理已过期优惠券
        HealthCouponList::disposeOverdueCoupon($this->auth->id);
    }

    /**
     * 我的优惠券
     * @Author 张旭鹏
     * @DateTime 2023-06-15
     */
    public function lists()
    {
        $limit    = $this->request->param('limit/d', 10);
        $status   = $this->request->param('status/d', 0);
        $paginate = HealthCouponList::with(['coupon'])
            ->where('user_id', $this->auth->id)
            ->where('status', $status)
            ->paginate($limit)
            ->each(function ($item) {
                $item->condition    = $item->coupon['condition_type'] == 1
                    ? '无金额门槛'
                    : '满' . intval($item->coupon['condition_money']) . '使用';
                $item->coupon_name  = $item->coupon['name'];
                $item->coupon_money = $item->coupon['money'];
                switch ($item->coupon['use_goods_type']) {
                    case 1:
                        $item->use_scene = '全场通用';
                        break;
                    case 2:
                        $item->use_scene = '指定商品可用';
                        break;
                }
                switch ($item->coupon['use_time_type']) {
                    case 1:
                        $item->effective_time =
                            date('Y.m.d H:i', $item->coupon['use_time_start']) . ' ~ ' .
                            date('Y.m.d H:i', $item->coupon['use_time_end']);
                        break;
                    case 2:
                        $item->effective_time = '有效期至' . date('Y年m月d日', $item['invalid_time']);
                        break;
                    case 3:
                        $item->effective_time = '领取次日' . $item->coupon['use_time'] . '天内可用';
                        break;
                }
                $item->visible(['condition', 'coupon_name', 'coupon_money', 'effective_time', 'use_scene', 'expiration_date']);
            });
        Db::name('health_tracking_monitor')->insert([
            'event_id'    => 11,
            'user_id'     => $this->auth->id ?: 0,
            'ip'          => $this->request->ip(),
            'create_time' => time()
        ]);
        $this->success('', $paginate);
    }

    /**
     * 订单选择优惠券列表
     * @Author 张旭鹏
     * @DateTime 2023-06-16
     */
    public function orderUse()
    {
        $params     = (new OrderValidate())->goCheck('confirm_info');
        $coupon     = HealthCouponList::with(['coupon'])
            ->where('user_id', $this->auth->id)
            ->where('status', 0)
            ->select();
        $use_coupon = [];
        $this->success('', $use_coupon);
    }
}
